import { memo, useEffect, useState } from 'react';
import { Input, Empty, Button } from 'antd';
import { SearchOutlined, ClockCircleOutlined, DeleteOutlined } from '@ant-design/icons';
import { motion, AnimatePresence } from 'framer-motion';
import { useNavigate } from 'react-router-dom';
import type { Article } from '@/types';
import { getMockAllArticles } from '@/Utils/localForage';
import { useDebounce } from '@/hooks/useDebounce';

const { Search } = Input;

export const SearchComponent = memo(() => {
  const navigate = useNavigate();
  const [articles, setArticles] = useState<Article[]>([]);
  const [searchKeyword, setSearchKeyword] = useState("");
  const [showHistory, setShowHistory] = useState<boolean>(false);
  const [searchHistory, setSearchHistory] = useState<string[]>([]);
  const [searchResults, setSearchResults] = useState<Article[]>([]);

  // 为了方便查看效果,设置为 3s
  const debouncedSearchKeyword = useDebounce(searchKeyword, 3000);

  // 加载文章数据
  useEffect(() => {
    const loadArticles = async () => {
      try {
        const articlesData = await getMockAllArticles();
        if (articlesData) {
          setArticles(articlesData);
        }
      } catch (error) {
        console.error('加载文章数据失败:', error);
      }
    };
    loadArticles();
  }, []);

  // 查询是否有匹配的数据
  const likeSearch = (value: string) => {
    if (value.trim()) {
      // 查找出标题,概要,作者名 有匹配的文章
      const result = articles.filter((article) => {
        return article.title.includes(value) || article.summary.includes(value) || article.author.username.includes(value)
      })
      setSearchResults(result)
    } else {
      setSearchResults([])
    }
  }

  // 监听防抖后的搜索关键词变化
  useEffect(() => {
    likeSearch(debouncedSearchKeyword);
  }, [debouncedSearchKeyword]);

  // 处理搜索输入
  const handleSearchInput = (value: string) => {
    setSearchKeyword(value)
  };

  // 处理搜索提交
  const handleSearchSubmit = (value: string) => {
    if (value.trim()) {
      navigate(`/search?q=${encodeURIComponent(value.trim())}`);
      setShowHistory(false)
      setSearchHistory([...new Set([...searchHistory, value])])
      setSearchKeyword('')

    }
  };

  // 点击搜索结果,跳转到对应的文章
  const handleResultClick = (id: string) => {
    navigate(`/article/${id}`);
    setSearchKeyword('')
    setSearchResults([])
    // 设置搜索历史 数组去重
    setSearchHistory([...new Set([...searchHistory, searchKeyword])])
  };

  // 高亮匹配文本
  const highlightText = (text: string, keyword: string) => {
    if (!keyword.trim()) return text;
    const regex = new RegExp(`(${keyword})`, 'gi');
    const parts = text.split(regex);
    return parts.map((part, index) =>
      regex.test(part) ? (
        <span key={index} className="bg-yellow-200 font-medium">
          {part}
        </span>
      ) : (
        part
      )
    );
  };

  // 清除历史
  const clearHistory = () => {
    setSearchHistory([])
  }
  // 清除单个历史记录
  const removeHistoryItem = (item: string) => {
    setSearchHistory(searchHistory.filter((history) => history !== item))
  }
  return (
    <div className="relative">
      <Search
        placeholder="搜索文章、作者..."
        value={searchKeyword}
        onChange={(e) => handleSearchInput(e.target.value)}
        onSearch={handleSearchSubmit}
        onFocus={() => setShowHistory(true)}
        onBlur={() => {
          setTimeout(() => setShowHistory(false), 200);
        }}
        enterButton={<SearchOutlined />}
        allowClear
      />

      {/* 搜索历史记录和结果 */}
      <AnimatePresence>
        {showHistory && (
          <motion.div
            initial={{ opacity: 0, y: -10 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -10 }}
            transition={{ duration: 0.2 }}
            className="absolute top-full left-0 right-0 bg-white border border-gray-200 rounded-lg shadow-lg z-50 max-h-96 overflow-hidden"
          >
            {/* 搜索历史 */}
            {searchHistory.length > 0 && !searchKeyword && (
              <div className="p-4 border-b border-gray-100">
                <div className="flex items-center justify-between mb-3">
                  <div className="flex items-center gap-2 text-sm text-gray-600">
                    <ClockCircleOutlined />
                    <span>搜索历史</span>
                  </div>
                  <Button
                    type="text"
                    size="small"
                    onClick={clearHistory}
                    className="text-gray-400 hover:text-red-500"
                  >
                    清除所有
                  </Button>
                </div>
                <div className="space-y-2">
                  {searchHistory.map((item) => (
                    <div
                      key={item}
                      className="flex items-center justify-between p-2 hover:bg-gray-50 rounded cursor-pointer group"
                    >
                      <div className="flex items-center gap-2 flex-1">
                        <ClockCircleOutlined className="text-gray-400" />
                        <span className="text-sm truncate">{item}</span>
                      </div>
                      <div className="flex items-center gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
                        <Button
                          type="text"
                          size="small"
                          icon={<DeleteOutlined />}
                          onClick={() => {
                            removeHistoryItem(item);
                          }}
                          className="text-gray-400 hover:text-red-500"
                        />
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* 搜索结果 */}
            {searchKeyword && (
              <div className='p-4'>
                {searchResults.length > 0 ? (
                  <div className="space-y-3">
                    <div className="text-sm text-gray-500">
                      找到 {searchResults.length} 个结果
                    </div>
                    {searchResults.slice(0, 5).map((article) => (
                      <div
                        key={article.id}
                        className="p-3 hover:bg-gray-50 rounded-lg cursor-pointer border border-transparent hover:border-gray-200 transition-all"
                        onClick={() => handleResultClick(article.id)}
                      >
                        <div className="flex items-start gap-3">

                          <div className="flex-1 min-w-0">
                            <div className="flex items-center gap-2 mb-1">
                              <h4 className="text-sm font-medium text-gray-900 truncate">
                                {highlightText(article.title, searchKeyword)}
                              </h4>
                            </div>
                          </div>
                        </div>
                      </div>
                    ))}
                    {searchResults.length > 5 && (
                      <div className="text-center pt-2 border-t border-gray-100">
                        <span className="text-sm text-gray-500">
                          还有 {searchResults.length - 5} 个结果，点击搜索查看更多
                        </span>
                      </div>
                    )}
                  </div>
                ) : (<div className="py-8">
                  <Empty
                    image={Empty.PRESENTED_IMAGE_SIMPLE}
                    description={
                      <span className="text-sm text-gray-500">
                        未找到相关结果
                      </span>
                    }
                  />
                </div>)}

              </div>

            )}

            {/* 无搜索关键词且无历史记录 */}
            {!searchKeyword && searchHistory.length === 0 && (
              <div className="p-4 text-center text-sm text-gray-500">
                暂无搜索历史
              </div>
            )}
          </motion.div>
        )}
      </AnimatePresence>
    </div >
  );
});

SearchComponent.displayName = 'SearchComponent'; 